package controllers;

import java.util.List;
import java.util.Random;

import models.CategoryModel;
import models.ProductModel;

import play.Logger;
import play.data.validation.Required;
import play.mvc.Controller;
import util.Contant;
import util.FsUtil;
import util.PaginationInfo;

public class Product extends Controller {

	//return page index.html in view/Product/index.html
	public static void index(int page) {
		List<ProductModel> totalProducts = ProductModel.listActiveProducts();
		int total = totalProducts.size();
		Logger.info("total product size >> " + totalProducts.size());
		if(page == 0){
			page = 1;
		}
		List<ProductModel> listProducts = ProductModel.getListProductLimit(totalProducts, page, Contant.PAGE_ITEM);	
		PaginationInfo paginationInfo = FsUtil.pagingInAdmin(page, total, "Product.index");
		List<CategoryModel> dongphucCategories = CategoryModel.listDongPhuc();
    	List<CategoryModel> bhldCategories = CategoryModel.listBHLD();
        render(listProducts,dongphucCategories, bhldCategories, paginationInfo);
    }
	
	//return list product follow category in page Product
	public static void listProduct(@Required String alias, int page) {
		List<ProductModel> totalProducts = ProductModel.listProductFollowCategory(alias);
		int total = totalProducts.size();
		Logger.info("total product size >> " + totalProducts.size());
		if(page == 0){
			page = 1;
		}
		List<ProductModel> listProducts = ProductModel.getListProductLimit(totalProducts, page, Contant.PAGE_ITEM);	
		PaginationInfo paginationInfo = FsUtil.pagingInAdmin(page, total, "Product.index");
		List<CategoryModel> dongphucCategories = CategoryModel.listDongPhuc();
    	List<CategoryModel> bhldCategories = CategoryModel.listBHLD();
    	String aliasCategory = alias;
        renderTemplate("Product/index.html",listProducts, dongphucCategories, bhldCategories, paginationInfo, aliasCategory);
    }
	
	//show detail product and render random 6 product
	public static void detail(@Required String alias){
		ProductModel product = ProductModel.findFollowAlias(alias);
		String aliasCategory = product.category;
		//get list product follow category
		List<ProductModel> totalProducts = ProductModel.listProductFollowCategory(aliasCategory);
		Logger.info("total product size >> " + totalProducts.size());
		List<ProductModel> listProducts = ProductModel.listProductRandom(totalProducts, Contant.PAGE_DETAIL_ITEM);	
		//get next random product
		Random r = new Random();
		ProductModel productNext = ProductModel.chooseProductRandom(r, totalProducts);
		while(productNext.equals(product) ){
			productNext = ProductModel.chooseProductRandom(r, totalProducts);
		}
		List<CategoryModel> dongphucCategories = CategoryModel.listDongPhuc();
    	List<CategoryModel> bhldCategories = CategoryModel.listBHLD();
		render(product, aliasCategory, dongphucCategories, bhldCategories, listProducts, productNext);
	}
}
